<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <!-- multiple上传多个文件，给input添加multiple -->
  <input type="file" name="" id="file1" multiple>
  <button id="btn">上传</button>
  <p id="percent" style="display: none;"><span>0</span>%</p>
  <img src="" id="img" alt="" style="width: 300px;">
  <script>
    btn.onclick = () => {
      //获取数组
      const fileList = file1.files
      //判断数组长度是否已经上传文件
      if (fileList.length <= 0) return alert('请上传文件')
      document.querySelector('#percent').style.display = 'block'
      const fd = new FormData()
      //将上传的文件追加到formData里面
      fd.append('avatar', fileList[0])
      const xhr = new XMLHttpRequest()
      //progress检测文件上传的事件(进度事件)
      xhr.upload.onprogress = e => {
        //e.lengthComputable判断是否有文件处于上传中
        //lengthComputable：返回一个布尔值，表示当前进度是否具有可计算的长度。如果为false，就表示当前进度无法测量。
        if (e.lengthComputable) {
          //e.loaded已经上传的字符
          //e.total字符总量
          const percent = Math.ceil((e.loaded / e.total) * 100)
          document.querySelector('#percent').children[0].innerHTML = percent
        }
        xhr.upload.onload = () => {
          document.querySelector('#percent').style.display = 'none'
        }
      }
      xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar')
      xhr.send(fd)
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 & xhr.status === 200) {
          if (JSON.parse(xhr.responseText).status !== 200) return alert('上传失败')
          img.src = 'http://www.liulongbin.top:3006' + JSON.parse(xhr.responseText).url
        }
      }
    }
  </script>
</body>

</html>